package com.feihong.txgw.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.feihong.txgw.R;

import java.io.File;
import java.net.URISyntaxException;
import java.util.List;

/**
 * @author wangziheng
 * @name txgw_app
 * @class name：com.feihong.txgw.dialog
 * @class describe: 调起外部三方地图应用
 * @time 2017/10/26 17:28
 * @change
 * @chang time
 * @class describe
 */
public class ChooseMapDialog extends Dialog {
    private Context mContext;
    /**
     * 顺序依次是  出发地纬度 经度  目的地纬度 经度
     */
    private List<String> mPosition;
    /**
     * 高德  百度 腾讯
     */
    private TextView mGDTv, mBDTv, mTXTv, mCannelTv;
    private LinearLayout mSubTitleParentLauout;

    public ChooseMapDialog(@NonNull Context context, List<String> data) {
        super(context, R.style.MyDialogStyleBottom);
        mPosition = data;
        mContext = context;

        initView();
    }

    private void initView() {
        setContentView(R.layout.user_change_sex);
        mSubTitleParentLauout = (LinearLayout) findViewById(R.id.dialog_Subtitle_parent_layout);
        mSubTitleParentLauout.setVisibility(View.VISIBLE);
        mGDTv = (TextView) findViewById(R.id.dialog_Title_tv);
        mBDTv = (TextView) findViewById(R.id.dialog_SubTitle_tv);
        mTXTv = (TextView) findViewById(R.id.dialog_Content_tv);
        mCannelTv = (TextView) findViewById(R.id.dialog_cannel_tv);
        mGDTv.setOnClickListener(chooseMapListener);
        mBDTv.setOnClickListener(chooseMapListener);
        mTXTv.setOnClickListener(chooseMapListener);
        mCannelTv.setOnClickListener(chooseMapListener);
        mCannelTv.setText("取消");
        setCanceledOnTouchOutside(false);
        if (!isAppInstalled("com.baidu.BaiduMap")) {
            mBDTv.setText("百度地图(未安装)");
        } else {
            mBDTv.setText("百度地图");
        }

        if (!isAppInstalled("com.autonavi.minimap")) {
            mGDTv.setText("高德地图(未安装)");
        } else {
            mGDTv.setText("高德地图");
        }

        if (!isAppInstalled("com.tencent.map")) {
            mTXTv.setText("腾讯地图(未安装)");
        } else {
            mTXTv.setText("腾讯地图");
        }
    }

    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }

    private boolean isAppInstalled(String uri) {
        PackageManager pm = mContext.getPackageManager();
        boolean installed = false;
        try {
            pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
            installed = true;
        } catch (PackageManager.NameNotFoundException e) {
            installed = false;
        }
        return installed;
    }

    public void setData(List<String> data) {
        mPosition = data;
    }

    private View.OnClickListener chooseMapListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.dialog_Title_tv:
                    StringBuffer stringBuffer = new StringBuffer();
                    for (String str : mPosition) {
                        stringBuffer.append(str + "   ");
                    }
                    LogUtils.i("通讯顾问 :" + "起点终点经纬度 --" + stringBuffer);
                    selectGaode("我的位置", mPosition.get(4));
                    break;
                case R.id.dialog_SubTitle_tv:
                    selectBaidu("我的位置", mPosition.get(4));
                    break;
                case R.id.dialog_Content_tv:
                    selectTencent("我的位置", mPosition.get(4));
                    break;
                case R.id.dialog_cannel_tv:
                    cancel();
                    break;
                default:
                    break;
            }
        }
    };

    private void selectBaidu(String startName, String endName) {
        try {
            //调起App
            if (isInstallByread("com.baidu.BaiduMap")) {
                double[] locationDes = gaoDeToBaidu(Double.parseDouble(mPosition.get(2)), Double.parseDouble(mPosition.get(3)));
                Intent intent = Intent.getIntent("intent://map/direction?" +
                        //"origin=latlng:"+"34.264642646862,108.95108518068&" +   //起点  此处不传值默认选择当前位置
                        //终点
                        "destination=latlng:" + locationDes[0] + "," + locationDes[1] + "|name:" + endName +
                        "&mode=drivingreferer=Autohome|GasStation#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                mContext.startActivity(intent);
                cancel();
            } else {
                Toast.makeText(mContext, "您还没有安装百度地图APP", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void selectGaode(String startName, String endName) {
        if (isInstallByread("com.autonavi.minimap")) {
            try {
                Intent intentOther = new Intent("android.intent.action.VIEW",
                        Uri.parse("amapuri://route/plan/?sid=BGVIS1&sname=" + startName + "&did=BGVIS2&dlat=" + mPosition.get(2) +
                                //跳转至路径规划
                                "&dlon=" + mPosition.get(3) + "&dname=" + endName + "&dev=0&t=1")
                        /*Uri.parse("androidamap://navi?sourceApplication=e游客&poiname=我的目的地&lat="
                                + mPosition.get(2) + "&lon=" +  mPosition.get(3) + "&dev=0&style=2")*/);//直接跳转至导航
                intentOther.addCategory("android.intent.category.DEFAULT");
                intentOther.setPackage("com.autonavi.minimap");
                intentOther.setAction("android.intent.action.VIEW");
                intentOther.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                mContext.startActivity(intentOther);
                cancel();
            } catch (Exception e) {
                Toast.makeText(mContext, "您还没有安装高德地图APP", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(mContext, "您还没有安装高德地图APP", Toast.LENGTH_SHORT).show();
        }
    }


    private void selectTencent(String startName, String endName) {

        if (isInstallByread("com.tencent.map")) {
            try {
                String URL = "qqmap://map/routeplan?type=drive&" +
                        "from=" + startName + "&fromcoord=" + mPosition.get(0) + "," + mPosition.get(1) + "&to=" + endName + "&" +
                        "tocoord=" + mPosition.get(2) + "," + mPosition.get(3) + "&policy=1&referer=" + mContext.getResources().getString(R.string.app_name);
                Intent intent = Intent.parseUri(URL, 0);
                intent.setComponent(null);
                intent.setSelector(null);
                mContext.startActivity(intent);
                cancel();
            } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Toast.makeText(mContext, "启动地图失败", Toast.LENGTH_SHORT).show();
                return;
            }
        } else {
            Toast.makeText(mContext, "您还没有安装腾讯地图APP", Toast.LENGTH_SHORT).show();
        }
    }

    public double[] gaoDeToBaidu(double gd_lon, double gd_lat) {
        double[] bd_lat_lon = new double[2];
        double PI = 3.14159265358979324 * 3000.0 / 180.0;
        double x = gd_lon, y = gd_lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * PI);
        bd_lat_lon[0] = z * Math.cos(theta) + 0.0065;
        bd_lat_lon[1] = z * Math.sin(theta) + 0.006;
        return bd_lat_lon;
    }

    public void showDialog() {
        show();
        WindowManager windowManager = ((Activity) mContext).getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); //设置宽度
        getWindow().setAttributes(lp);
    }

}
